package com.bole.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bole.Thread.CarpageThred;
import com.bole.dto.car.TbCarDto;
import com.bole.dto.car.TbCarInfoDto;
import com.bole.dto.img.TbCarImgDto;
import com.bole.feign.CarFeign;
import com.bole.feign.CarInfoFeign;
import com.bole.feign.TbCarImgFeign;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RocketMQMessageListener(topic = "BOLE",consumerGroup = "consumerGroup1", messageModel = MessageModel.BROADCASTING)
public class CarPageServiceImpl  implements RocketMQListener<String> {

    //注入freemarker配置类
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${freemarker.outPath}")
    private String outPath;

    @Autowired
    private CarFeign carFeign;

    @Autowired
    private TbCarImgFeign carImgFeign;

    @Autowired
    private CarInfoFeign carInfoFeign;


    @Override

    public void onMessage(String s) {
        System.out.println("进入方法");
        //加载配置创建模板
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        List<Long> longs = JSONObject.parseArray(s, Long.class);
        // List转成数组
        Long[] ids = longs.toArray(new Long[0]);
        for (Long carId : ids) {
            FileWriter fileWriter = null;
            Template template = null;

            try {
                template = configuration.getTemplate("car.ftl");
                //创建数据模型对象
                Map map = new HashMap();
                TbCarImgDto imgDto = carImgFeign.findByCarId(carId);
                TbCarDto carDto = carFeign.getCarById(carId);
                TbCarInfoDto carInfo = carInfoFeign.getCarInfoById(carId);
                map.put("imgDto", imgDto);
                map.put("carDto", carDto);
                map.put("carInfo", carInfo);
                new Thread(new CarpageThred(template,map,outPath,carId)).start();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}


